package com.qianchang.microfinance.view.hsbindbank;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.OpenAccDataBean;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.widgets.WebLayout;
import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;

import org.json.JSONException;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 版 权: 广西鸿胜科技有限公司
 * 描 述: 新网银行第一次开户的授权
 * 修 改 人: chen G L
 * 修改时间: 2018/1/9 16:33
 */

public class HSAuthorizedActivity extends BaseActivity{

//    @BindView(R.id.webView_id)
//    WebView webView;
//    @BindView(R.id.progressBarLoading)
//    ProgressBar mLoadingProgress;

    private String url = "";
    private String urlParameter = "";
    private String sign = "";
    private String platformNo = "";
    private String userDevice = "";
    private String keySerial = "";
    private String reqData = "";
    private String serviceName = "";

    private OpenAccDataBean openAccDataBean;

    private LinearLayout mLinearLayout;
    protected AgentWeb mAgentWeb;
    private boolean isConfirmlGoing = false;

    public boolean isConfirmlGoing() {
        return isConfirmlGoing;
    }

    public void setConfirmlGoing(boolean confirmlGoing) {
        isConfirmlGoing = confirmlGoing;
    }



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hsbindbankcard_layout);
//        ButterKnife.bind(this);
        initView();

    }


    @Override
    protected void initView() {
        super.initView();
        setTitleName("绑定银行卡");

        mLinearLayout = (LinearLayout) findViewById(R.id.mcontainer);


        mAgentWeb = AgentWeb.with(this)//
                .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))//
                .useDefaultIndicator()//
                .setWebChromeClient(mWebChromeClient)
                .setWebViewClient(mWebViewClient)
                .setMainFrameErrorView(R.layout.agentweb_error_page, -1)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                .setWebLayout(new WebLayout(this))
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.ASK)//打开其他应用时，弹窗咨询用户是否前往其他应用
                .interceptUnkownScheme() //拦截找不到相关页面的Scheme
                .createAgentWeb()//
                .ready()
                .go(url);

        if(mAgentWeb!=null){
            //注入对象
            mAgentWeb.getJsInterfaceHolder().addJavaObject("android",new AndroidInterface(mAgentWeb,HSAuthorizedActivity.this));
        }

        Bundle bundle = getBundle();
        if (null != bundle) {
            openAccDataBean = (OpenAccDataBean) bundle.getSerializable(ConstantAppInfo.OPEN_ACCOUNT_BEAN);
            isConfirmlGoing = bundle.getBoolean("isConfirml",false);
            if (openAccDataBean == null) {
                openAccDataBean = new OpenAccDataBean();
            } else {
                url = openAccDataBean.getAction();
                sign = openAccDataBean.getSign();
                platformNo = openAccDataBean.getPlatformNo();
                userDevice = openAccDataBean.getUserDevice();
                keySerial = openAccDataBean.getKeySerial();
                reqData = openAccDataBean.getReqData();
                serviceName = openAccDataBean.getServiceName();
            }
        }


        try {
            initWebView();
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    }

    private String getParameter() throws JSONException, UnsupportedEncodingException {
        Map<String,String> map = new HashMap<String,String>();
        Log.i("TAG","sign = "+sign+" platformNo = "+platformNo+" userDevice = "+userDevice+" keySerial = "+keySerial+" reqData = "+reqData+" serviceName = "+serviceName );
        map.put("sign",sign);
        map.put("platformNo",platformNo);
        map.put("userDevice",userDevice);
        map.put("keySerial",keySerial);
        map.put("reqData",reqData);
        map.put("serviceName",serviceName);
        String parameter = "";
        String subParameter = "";

        Iterator entries = map.entrySet().iterator();
        while (entries.hasNext()) {
            Map.Entry entry = (Map.Entry) entries.next();
            String key = (String) entry.getKey();
            String value = (String) entry.getValue();
            parameter = parameter + key + "=" + URLEncoder.encode(value,"utf-8") + "&";
        }
        subParameter = parameter.substring(0, parameter.length() - 1);
        return subParameter;
    }



    String pars = "";
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() throws JSONException, UnsupportedEncodingException {

        pars = getParameter();
        mAgentWeb.getLoader().postUrl(url,pars.getBytes());


//        WebSettings settings = webView.getSettings();
//        settings.setDefaultTextEncodingName("utf-8");       //设置网页默认编码
//        settings.setLoadWithOverviewMode(true);
//        settings.setJavaScriptEnabled(true);                //支持javaScript
//        settings.setJavaScriptCanOpenWindowsAutomatically(true);
//        webView.getSettings().setDomStorageEnabled(true);
//
//        webView.post(new Runnable() {
//            @Override
//            public void run() {
//                webView.postUrl(url,pars.getBytes());
//            }
//        });


    }


    private WebChromeClient mWebChromeClient = new WebChromeClient() {

        @Override
        public void onProgressChanged(WebView view, int newProgress) {

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            setTitle(title);
        }
    };

    private WebViewClient mWebViewClient = new WebViewClient() {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            Log.i("Info", "BaseWebActivity onPageStarted");
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (mAgentWeb.handleKeyEvent(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        mAgentWeb.getWebLifeCycle().onPause();
        super.onPause();

    }

    @Override
    protected void onResume() {
        mAgentWeb.getWebLifeCycle().onResume();
        super.onResume();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        //mAgentWeb.destroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
    }


}
